package com.weiyi.weiman.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.weiyi.weiman.domain.dto.ResultInfo;
import com.weiyi.weiman.domain.status.ResultStatus;
import com.weiyi.weiman.exception.APIException;
import com.weiyi.weiman.service.comics.ComicsUploadService;
import com.weiyi.weiman.utils.FastDFSUtils;
import com.weiyi.weiman.utils.RedisUtils;
import com.weiyi.weiman.utils.ResultUtils;
import comics.Comics;
import comics.ComicsChapter;
import comics.ComicsPicture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @Author zhang
 * @Date 2021/5/7 上午9:55
 * @Description 文件上传和下载的类
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FastDFSUtils fastDFSUtils;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ComicsUploadService comicsUploadService;

    @PostMapping("/createComics")
    public ResultInfo createComics(@RequestBody Comics comics) {
        //判断是否缺少创建漫画的必要信息
        if (StringUtils.isEmpty(comics.getComicsName()) ||
                StringUtils.isEmpty(comics.getComicsAuthor()) ||
                StringUtils.isEmpty(comics.getComicsCover()) ||
                StringUtils.isEmpty(comics.getComicsLabel()) ||
                StringUtils.isEmpty(comics.getComicsIntroduction())) {
            log.error("上传漫画必要信息有缺失");
            return ResultUtils.failureInfo(ResultStatus.INFORMATION_LACK_ERROR);
        }
        //上传封面到服务器中
        File cover = new File(comics.getComicsCover());
        if (isImage(cover)) {
            try {
                String address = fastDFSUtils.uploadFile(cover);
                comics.setComicsCover(address);
            } catch (Exception e) {
                log.error("漫画封面上传失败", e);
                return ResultUtils.failureInfo(ResultStatus.IMAGE_UPLOAD_ERROR);
            }
        } else {
            log.error("上传漫画的封面格式错误");
            return ResultUtils.failureInfo(ResultStatus.IMAGE_FORMAT_ERROR);
        }
        if (comicsUploadService.insert(comics)) {
            log.info("漫画写入数据库成功");
            return ResultUtils.successInfo(comics);
        } else {
            log.error("漫画写入数据库错误");
            return ResultUtils.failureInfo(ResultStatus.DB_WRITE_ERROR);
        }
    }

    /**
     * 单个章节上传
     * @param chapter
     * @return
     */
    @PostMapping("/singleUpload")
    public ResultInfo singleUpload(@RequestBody ComicsChapter chapter
            , @RequestParam("folderPath") String folderPath) {
        List<ComicsPicture> comicsPictures = null;
        try {
            comicsPictures = comicsUploadService.uploadChapter(chapter, folderPath);
            for (ComicsPicture comicsPicture : comicsPictures) {
                if (!Objects.isNull(comicsPicture)) {
                    String thumbImageTokenUrl = fastDFSUtils.getThumbImageTokenUrl(comicsPicture.getPictureAddress());
                    comicsPicture.setPictureAddress(thumbImageTokenUrl);
                }
            }
        } catch (APIException e) {
            return ResultUtils.failureInfo(e.getResultStatus());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.failureInfo(e.getMessage());
        }
        return ResultUtils.successInfo(comicsPictures);
    }

    @RequestMapping("/pic")
    @ResponseBody
    public ResultInfo uplodFile(@RequestParam("file") MultipartFile[] file) throws Exception {
        for (int i = 0; i < file.length; i++) {
            String originalFilename = file[i].getOriginalFilename();
            InputStream inputStream = file[i].getInputStream();
        }
        return null;
    }

    /**
     * 判断文件是否是图片
     * @param file
     * @return
     */
    private boolean isImage(File file) {
        if (!file.exists()) {
            return false;
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(file);
            if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
